package com.qf.strategy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.dao.DrugMapper;
import com.qf.dao.DrugOrderMapper;
import com.qf.dao.MedicleSeckillDrugMapper;

import com.qf.pojo.entity.MedicleDrug;
import com.qf.pojo.entity.MedicleOrder;
import com.qf.pojo.entity.MedicleOrderitem;

import com.qf.pojo.req.PayReq;
import com.qf.pojo.resp.Resultmsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName PayFactory
 * @Description
 * @Author lanzhike
 * @Date 2023/7/30 19:51
 * @Version 1.0
 */
@Component
public class PayFactory {

    @Resource(name = "AliPay")
    PayService AliPayServiceImpl;
    @Resource(name = "WeChat")
    PayService WeChatServiceImpl;
    @Autowired
    DrugOrderMapper drugOrderMapper;
    @Autowired
    DrugMapper drugMapper;

    public static final Map map = new HashMap<>();

    @PostConstruct
    public void initPayType(){
        map.put("AliPay",AliPayServiceImpl);
        map.put("WeChat",WeChatServiceImpl);
    }

    public Resultmsg pay(PayReq payReq){
        Object o = map.get(payReq.getPayType());
        if (o == null){
            Resultmsg.fail("不支持该支付方式");
        }
        PayService payService = (PayService) o;
        QueryWrapper<MedicleOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("transaction_id",payReq.getTransactionId());
        MedicleOrder tbSeckillOrder = drugOrderMapper.selectOne(wrapper);
        if (tbSeckillOrder == null){
            return Resultmsg.fail("没有该订单");
        }
        QueryWrapper<MedicleDrug> wrapper1 = new QueryWrapper<>();
        for (MedicleOrderitem orderItem : tbSeckillOrder.getOrderItems()) {
            wrapper1.eq("drug_id",orderItem.getDrugId());
            MedicleDrug medicleDrug = drugMapper.selectOne(wrapper1);
        }

//        设置支付方式,支付时,将支付方式传入数据库中
        tbSeckillOrder.setPayType(payReq.getPayType());
        tbSeckillOrder.setCreateTime(new Date());
        tbSeckillOrder.setPayTime(new Date());
        drugOrderMapper.updateById(tbSeckillOrder);

        String transactionId = tbSeckillOrder.getTransactionId();
        Resultmsg pay = payService.pay(Long.valueOf(transactionId), Double.parseDouble(tbSeckillOrder.getOrderMoney()), tbSeckillOrder.getUserId().toString());
        return pay;

    }
}
